<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/14
 * Time: 11:16
 */

namespace App\Task;

use App\Sock\Logic\Game as GameLogic;
use Composer\Config;
use EasySwoole\Core\Component\Cache\Cache;
use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Swoole\ServerManager;
use EasySwoole\Core\Swoole\Task\AbstractAsyncTask;

/**
 * 发送广播消息
 * Class BroadcastTask
 * @package App\Task
 */
class Broadcast extends AbstractAsyncTask
{


    /**
     * 执行投递
     * @param $taskData
     * @param $taskId
     * @param $fromWorkerId
     * @return bool
     */
    function run($taskData, $taskId, $fromWorkerId)
    {
        if (isset($taskData['type'])) {
            call_user_func([$this, $taskData['type'] . '_broadcast'], $taskData);
//            $this->$taskData.'Cast';
            return false;
        }
        $users = [];
        $roomid = isset($taskData['room_id']) ? $taskData['room_id'] : 0;
        if (empty($roomid)) {
//            $users = Game::
            //获取所有RoomUUID
            $room_list = Cache::getInstance()->get('room_list');
            foreach ($room_list as $item => $value) {
                $user[] = GameLogic::selectRoomFd($value['room_uuid']);
            }
            if (!empty($user)) {
                if (count($user) == 1) {
                    $users = $user[0];
                } else {
                    $users = [];
                    foreach ($user as $items => $list) {
                        foreach ($list as $ii => $vv) {
                            $users[] = $vv;
                        }
                    }
                }
            }


        } else {
            $users = GameLogic::selectRoomFd($roomid);
        }


        /** @var \swoole_websocket_server $server */
        $this->sendMessage($users, $taskData);
        return true;
    }

    function sendMessage($users, $taskData, $ext_arr = [])
    {
        $server = ServerManager::getInstance()->getServer();
        foreach ($users as $userFd) {

            $connection = $server->connection_info($userFd);

            if ($connection['websocket_status'] == 3) { // 用户正常在线时可以进行消息推送
                $server->push($userFd, $taskData['payload']);
            }
        }
    }

    function draw_coin_broadcast($taskData)
    {
        $room_uuid = $taskData['room_uuid'];
        $except_uuid = $taskData['except_uuid'];
        $users = GameLogic::selectRoomFd($room_uuid);
        $except_fd[] = GameLogic::getUserFd($except_uuid);
        $this->sendMessage($users, $taskData, $except_fd);
        unset($except_fd);
        return true;
    }

    function finish($result, $task_id)
    {
        // TODO: Implement finish() method.
    }
}